﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessObjects.Objects;
using Persistency.DataAccess;
using System.Data;

namespace Persistency.DAL
{
	public static class AdressDAL
	{
		#region Members

		private const string SaveAdressStatement = @"dbo.SaveAdressen";
		private const string GetAdressStatement = @"dbo.GetAdressen";
		private const string GetOrganisationAdressStatement = @"dbo.GetAdressenListe";

		#endregion

		#region Methods

		public static void SaveAdress(AdressObject adressObject)
		{
			IDictionary<string, object> parameters = GetParameters(adressObject);
			SQLHelper.ExecuteStoredProcedure(SaveAdressStatement, parameters);
		}

		#endregion

		#region Functions

		public static AdressObject ConvertToAdress(DataRow row)
		{
			AdressObject adressObject = new AdressObject();
			adressObject.AdressID = (Guid)row["AdressID"];
			adressObject.AdressType = (string)row["AdressType"];
			adressObject.Strasse = (string)row["Strasse"];
			adressObject.Postleitzahl = (string)row["Postleitzahl"];
			adressObject.Ort = (string)row["Ort"];
            adressObject.OrgKey = (Int32)row["OrgKey"];

			return adressObject;
		}

		public static List<AdressObject> ConvertToOrganisationAdressen(DataTable dataTable)
		{
			List<AdressObject> organisationAdressen = new List<AdressObject>();
			foreach (DataRow row in dataTable.Rows)
			{
				organisationAdressen.Add(ConvertToAdress(row));
			}
			return organisationAdressen;
		}

		public static AdressObject GetAdress(Guid adressID)
		{
			AdressObject ret = null;
			IDictionary<string, object> parameters = new Dictionary<string, object>();
			parameters.Add("@inAdressID", adressID);
			DataTable dataTable = SQLHelper.ExecuteDataTable(GetAdressStatement, parameters);
			if (dataTable != null & dataTable.Rows.Count > 0)
			{
				DataRow dataRow = dataTable.Rows[0];
				ret = ConvertToAdress(dataRow);
			}
			
			return ret;
		}


		public static List<AdressObject> GetOrganisationAdressen(int orgKey)
		{
			IDictionary<string, object> parameters = new Dictionary<string, object>();
			parameters.Add("@inOrgKey", orgKey);
			DataTable dataTable = SQLHelper.ExecuteDataTable(GetOrganisationAdressStatement, parameters);
			return ConvertToOrganisationAdressen(dataTable);
		}

		private static IDictionary<string, object> GetParameters(AdressObject adressObject)
		{
			IDictionary<string, object> parameters = new Dictionary<string, object>();
			parameters.Add("@inAdressID", adressObject.AdressID);
			parameters.Add("@inAdressType", adressObject.AdressType);
			parameters.Add("@inPostleitzahl", adressObject.Postleitzahl);
            parameters.Add("@inOrt", adressObject.Ort);
			parameters.Add("@inOrgKey", adressObject.OrgKey);
			parameters.Add("@inStrasse", adressObject.Strasse);
			return parameters;
		}

		#endregion

	}
}
